<script setup lang="ts">
import {
  NForm,
  NFormItem,
  NInput,
  NButton,
  NIcon,
  type DataTableColumns,
  NDataTable,
  NSelect,
  type UploadFileInfo,
  useMessage,
  NModal,
  type FormInst,
  type SelectOption,
  NRadioGroup,
  NRadioButton,
  NScrollbar,
  NInputNumber,
  NDatePicker,
  NTreeSelect,
  type FormItemRule,
  NTooltip
} from 'naive-ui'
import { h, onMounted, reactive, ref, shallowRef, computed, watch } from 'vue'
import FixedAction from '@/components/FixedAction.vue'
import useRouteReplace from '@/hooks/useRouteReplace'
import { useRoute } from 'vue-router'
import type { BatchDetailModel } from '@/api/batchV2'
import type { IdentifyInfoModel, IdentifyFormModel, IdentifySubItemModel } from '@/api/batch'
import type { DicTreeModel } from '@/api/dic'
import type { HttpResponse, HttpResponsePagination } from '@/utils/http'
import { sendRequest } from '@/utils/api'
import ModalCard from '@/components/ModalCard.vue'
// import VUploader from '@/components/VUploaderV3/VUploader.vue'
import FileList from '@/components/FileList.vue'
import { ArrowRightAltFilled } from '@vicons/material'
// import type { CustomFile } from '@/components/VUploaderV3/types'
import VAttachments from '@/views/OA/Common/Attachments.vue'
import BatchCres from './components/BatchCres.vue'
import FUploader from './components/FUploader.vue'

const route = useRoute()
const routeReplace = useRouteReplace(route.query.redirect as string)
const isFromRecord = route.query.from === 'record'
const message = useMessage()

const validate = (form: FormInst | null): Promise<void> => {
  if (!form) return Promise.resolve()

  return new Promise((resolve, reject) => {
    form.validate((error) => {
      if (error) {
        reject()
      } else {
        resolve()
      }
    })
  })
}

const formData = ref({} as IdentifyFormModel)
const hzFormInst = shallowRef<FormInst | null>(null)
const submitLoading = ref(false)
const handleSubmit = async () => {
  if (submitLoading.value) return
  await Promise.all([validate(filesFormInst.value), validate(hzFormInst.value)])

  const files: Record<string, string> = {}
  filesFormData.forEach((e) => {
    files[e.key] = e.value
      // @ts-ignore
      .filter((e) => e.file?.remoteId)
      // @ts-ignore
      .map((e) => e.file.remoteId)
      .join(',')
  })

  try {
    submitLoading.value = true
    const [error, res] = await sendRequest<HttpResponse<IdentifyInfoModel>>({
      module: 'batch',
      api: 'identifyRegister',
      override: {
        data: {
          ...formData.value,
          ...files,
          identifyId: baseInfo.value.id
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    message.success(res.msg)
    window.flags.flushBatch = true
    routeReplace()
  } catch (error: any) {
    message.error(error.message)
  } finally {
    submitLoading.value = false
  }
}

const fileList = ref<UploadFileInfo[]>([])
const queryFileList = async (filesIds: string) => {
  try {
    const [error, res] = await sendRequest<
      HttpResponse<
        {
          name: string
          path: string
          id: string
          type: string
        }[]
      >
    >({
      module: 'upload',
      api: 'list',
      override: {
        params: {
          ids: filesIds
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)

    return res.data.map((e) => ({
      id: e.id,
      path: e.path,
      name: e.name,
      url: e.path,
      status: 'success'
    })) as unknown as UploadFileInfo[]
  } catch (error) {
    return []
  }
}

const baseInfo = shallowRef({} as IdentifyInfoModel)
const isTF = ref(false)
const queryBaseInfo = async () => {
  try {
    const [error, res] = await sendRequest<HttpResponse<IdentifyInfoModel>>({
      module: 'batch',
      api: isFromRecord ? 'identifyDetailByIdentifyId' : 'identifyDetail',
      override: {
        params: isFromRecord
          ? { identifyId: route.params.id }
          : {
              batchId: route.params.id
            }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    if (res.data.identifyTime) {
      res.data.identifyTime = res.data.identifyTime.split(' ')[0]
    }
    baseInfo.value = res.data
    isTF.value = res.data.identifyTypeCode === 'A3101'

    if (isFromRecord) queryAttachments()
    if (baseInfo.value.fileIds) fileList.value = await queryFileList(baseInfo.value.fileIds)
    queryTableData()
    queryDetailTableData()
  } catch (error) {
    console.log(error)
  }
}

const collectorName = ref<string | null>(null)
const batchFileList = ref<UploadFileInfo[]>([])
const batchInfo = ref({} as BatchDetailModel)
const queryBatchInfo = async () => {
  const [error, res] = await sendRequest<HttpResponse<BatchDetailModel>>({
    module: 'batchV2',
    api: 'detail',
    override: {
      params: {
        id: isFromRecord ? route.query.batchId : route.params.id
      }
    }
  })
  if (error) return message.error(error.message)

  sendRequest({
    module: 'clue',
    api: 'infoManage',
    uri: {
      id: res.data.clueId
    }
  })
    .then(([_, cr]) => {
      if (cr) {
        sendRequest({
          module: 'collector',
          api: 'info',
          uri: {
            id: cr.data.collectorId
          }
        })
          .then(([_, er]) => {
            if (er) collectorName.value = er.data.userName
          })
          .catch(() => (collectorName.value = null))
      }
    })
    .catch(() => (collectorName.value = null))

  if (res.data?.endTime) {
    res.data.endTime = res.data.endTime.slice(0, 10)
  }
  if (res.data?.startTime) {
    res.data.startTime = res.data.startTime.slice(0, 10)
  }
  if (res.data?.solicitNum) {
    res.data.solicitNum = Number(res.data.solicitNum)
  }
  batchInfo.value = res.data || {}
  if (res.data?.fileIds) batchFileList.value = await queryFileList(res.data.fileIds)
}

const clueSelectOptions = ref<SelectOption[]>([])
const clueSelectLoading = ref(false)
const queryClueSelectOptions = async () => {
  clueSelectLoading.value = true
  try {
    const [error, res] = await sendRequest<HttpResponse<DicTreeModel[]>>({
      module: 'batchV2',
      api: 'clueList'
    })

    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    clueSelectOptions.value = res.data
  } catch (error) {
    console.error(error)
  } finally {
    clueSelectLoading.value = false
  }
}

const clueMethodOptions = reactive<DicTreeModel[]>([])
const clueMethodLoading = ref(false)
const queryClueMethodOptions = async () => {
  clueMethodLoading.value = true
  try {
    const [error, res] = await sendRequest<HttpResponse<DicTreeModel[]>>({
      module: 'dic',
      api: 'getTree',
      override: {
        params: {
          dicCode: 'A30'
        }
      }
    })

    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    clueMethodOptions.length = 0
    clueMethodOptions.push(...(res.data[0] ? res.data[0].children || [] : []))
  } catch (error) {
    console.error(error)
  } finally {
    clueMethodLoading.value = false
  }
}

const summaryBatchModalVisible = ref(false)
const summaryBatchModalLoading = ref(false)
const editTableIds = ref<number[]>([])
const summaryBatchModalFormInst = shallowRef<FormInst | null>(null)
const summaryBatchModalFormData = ref({
  authenticity: '',
  opinion: ''
})
const handleSummaryBatchModalSubmit = () => {
  summaryBatchModalFormInst.value?.validate(async (error) => {
    if (error) return
    try {
      summaryBatchModalLoading.value = true
      const [error, res] = await sendRequest<HttpResponse<IdentifySubItemModel>>({
        module: 'batch',
        api: 'summaryBatch',
        override: {
          data: {
            authenticity: summaryBatchModalFormData.value.authenticity,
            identifyId: baseInfo.value.id,
            opinion: summaryBatchModalFormData.value.opinion,
            subItemIds: editTableIds.value
          }
        }
      })
      if (error) throw error
      if (res.code !== 0) throw new Error(res.msg)
      message.success(res.msg)
      handleSummaryBatchModalClose()
      queryTableData()
    } catch (error: any) {
      message.error(error.message)
    } finally {
      summaryBatchModalLoading.value = false
    }
  })
}
const handleSummaryBatchModalClose = () => {
  summaryBatchModalVisible.value = false
  summaryBatchModalFormData.value = {
    authenticity: '',
    opinion: ''
  }
  summaryBatchModalFormInst.value?.restoreValidation()
}

const editTableRow = shallowRef<IdentifySubItemModel | null>(null)
const isEditCurrent = (row: IdentifySubItemModel) => editTableRow.value?.id === row.id
const summaryBatchLoading = ref(false)
const handleSummaryBatch = async (index: number) => {
  if (errorIndexSet.has(index)) return
  try {
    summaryBatchLoading.value = true
    if (!editTableRow.value) return
    const [error, res] = await sendRequest<HttpResponse<IdentifySubItemModel>>({
      module: 'batch',
      api: 'summaryBatch',
      override: {
        data: {
          authenticity: editTableRow.value.authenticity,
          identifyId: baseInfo.value.id,
          opinion: editTableRow.value.opinion,
          subItemIds: [editTableRow.value.id]
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    message.success(res.msg)
    editTableRow.value = null
    queryTableData()
  } catch (error: any) {
    message.error(error.message)
  } finally {
    summaryBatchLoading.value = false
  }
}

const errorIndexSet = new Set()
const tableData = ref<IdentifySubItemModel[]>([])
const tableLoading = ref(false)
const columns: DataTableColumns<IdentifySubItemModel> = [
  {
    type: 'selection'
  },
  {
    title: '序号',
    key: 'index',
    width: 80,
    align: 'center',
    render: (_, index) => index + 1
  },
  {
    title: '征集品编码',
    key: 'subItemCode'
  },
  {
    title: '征集品名称',
    key: 'itemName'
  },
  {
    title: '类型',
    key: 'itemType'
  },
  {
    title: () => {
      return h('span', null, [
        h('span', { style: 'color: red; margin-right: 0.5em' }, '*'),
        h('span', null, '征集品真伪')
      ])
    },
    key: 'authenticity',
    render(e) {
      if (!isEditCurrent(e)) {
        if (e.authenticity === null) return null
        return e.authenticity === '0' ? '真' : e.authenticity === '1' ? '伪' : '无法确定'
      }
      return h(
        NSelect,
        // @ts-ignore
        {
          size: 'small',
          placeholder: '请选择',
          options: [
            { label: '真', value: '0' },
            { label: '伪', value: '1' },
            { label: '无法确定', value: '2' }
          ],
          value: e._authenticity,
          onUpdateValue: (value: string) => {
            e._authenticity = value as string
          }
        },
        null
      )
    }
  },
  {
    title: '意见',
    key: 'opinion',
    render(e, i) {
      if (!isEditCurrent(e)) return e.opinion
      return h(
        NFormItem,
        {
          rule: {
            trigger: ['blur', 'input'],
            message: `不能超过20字`,
            validator: () => {
              const pass = e._opinion ? e._opinion.length <= 20 : true
              if (!pass) errorIndexSet.add(i)
              else errorIndexSet.delete(i)
              return pass
            }
          }
        },
        {
          default: () =>
            h(NInput, {
              size: 'small',
              placeholder: '请输入',
              value: e._opinion,
              onUpdateValue: (value: string) => {
                if (!value) return (e._opinion = value)
                e._opinion = value
              }
            })
        }
      )
    }
  },
  {
    title: '操作',
    key: 'action',
    width: '200rem',
    align: 'center',
    fixed: 'right',
    render: (e, i) => {
      return editTableRow.value && isEditCurrent(e)
        ? [
            h(
              NButton,
              {
                color: '#6CB187',
                quaternary: true,
                size: 'small',
                style: 'margin-right: 10rem',
                loading: summaryBatchLoading.value,
                onClick: () => {
                  if (e._authenticity) e.authenticity = e._authenticity
                  if (errorIndexSet.has(i)) return
                  else if (e._opinion) e.opinion = e._opinion
                  handleSummaryBatch(i)
                }
              },
              { default: () => '确定' }
            ),
            h(
              NButton,
              {
                color: '#6CB187',
                quaternary: true,
                size: 'small',
                onClick: () => {
                  e._authenticity = null
                  e._opinion = null
                  errorIndexSet.delete(i)
                  editTableRow.value = null
                }
              },
              { default: () => '取消' }
            )
          ]
        : [
            h(
              NButton,
              {
                color: '#6CB187',
                quaternary: true,
                size: 'small',
                onClick: () => {
                  e._authenticity = e.authenticity
                  e._opinion = e.opinion
                  editTableRow.value = e
                }
              },
              { default: () => '编辑' }
            )
          ]
    }
  }
]
const queryTableData = async () => {
  try {
    tableLoading.value = true
    const [error, res] = await sendRequest<HttpResponsePagination<IdentifySubItemModel>>({
      module: 'batch',
      api: 'identifySubItems',
      override: {
        params: {
          identifyId: baseInfo.value.id,
          limit: 10000000,
          page: 1
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    tableData.value = res.data.list
  } catch (error) {
    console.log(error)
  } finally {
    tableLoading.value = false
  }
}

const checkIds = ref<number[]>([])
const activeTableRow = ref<IdentifySubItemModel | null>()
const identifyBatchInfos = computed<IdentifySubItemModel[]>(() => {
  if (activeTableRow.value) return [activeTableRow.value]
  return detailTableData.value.filter((e) => checkIds.value.includes(e.id))
})
const identifyBatchFormInst = shallowRef<FormInst | null>(null)
const identifyBatchFormData = ref<any[]>([])
const identifyBatchModalVisible = ref(false)
const identifyBatchModalLoading = ref(false)

watch(identifyBatchModalVisible, (v) => {
  if (!v) activeTableRow.value = null
})

const isDefine = (v: unknown) => v !== null && v !== undefined
const setIdentifyBatchFormData = () => {
  identifyBatchFormData.value = exportModelList.value.map((e) => ({
    expertId: e.id,
    opinion: e.opinion,
    minIdentifyValue: isDefine(e.minIdentifyValue) ? parseFloat(e.minIdentifyValue) : null,
    maxIdentifyValue: isDefine(e.maxIdentifyValue) ? parseFloat(e.maxIdentifyValue) : null,
    status: e.status
  }))
}
const handleIdentifyBatchModalSubmit = () => {
  identifyBatchFormInst.value?.validate(async (error) => {
    if (error) return
    try {
      identifyBatchModalLoading.value = true
      const [error, res] = await sendRequest<HttpResponse<IdentifySubItemModel>>({
        module: 'batch',
        api: 'identifyBatch',
        override: {
          data: {
            expertIdentifyList: identifyBatchFormData.value,
            identifyId: baseInfo.value.id,
            subItemIds: identifyBatchInfos.value.map((e) => e.id)
          }
        }
      })
      if (error) throw error
      if (res.code !== 0) throw new Error(res.msg)
      message.success(res.msg)
      handleIdentifyBatchModalClose()
      queryDetailTableData()
    } catch (error: any) {
      message.error(error.message)
    } finally {
      identifyBatchModalLoading.value = false
    }
  })
}
const handleIdentifyBatchModalOpen = () => {
  identifyBatchModalVisible.value = true
  queryExportModelList()
}
const handleIdentifyBatchModalClose = () => {
  identifyBatchModalVisible.value = false
  activeTableRow.value = null
  setIdentifyBatchFormData()
}

const detailTableData = ref<IdentifySubItemModel[]>([])
const detailTableLoading = ref(false)
// @ts-ignore
const detailColumns = computed<DataTableColumns<IdentifySubItemModel>>(() => {
  return [
    {
      type: 'selection'
    },
    {
      title: '序号',
      key: 'index',
      width: 80,
      align: 'center',
      // @ts-ignore
      render: (_, index) => index + 1
    },
    {
      title: '征集品编码',
      key: 'subItemCode'
    },
    {
      title: '征集品名称',
      key: 'itemName'
    },
    {
      title: '类型',
      key: 'itemType'
    },
    {
      title: '价格区间（元）',
      key: 'identifyValue'
    },
    {
      title: '接收时间',
      key: 'receiveTime'
    },
    {
      title: '移交人',
      key: 'transferUser'
    },
    {
      title: '操作',
      key: 'action',
      width: '150rem',
      align: 'center',
      fixed: 'right',
      // @ts-ignore
      render: (e) => [
        h(
          NButton,
          {
            color: '#6CB187',
            quaternary: true,
            size: 'small',
            onClick: () => {
              activeTableRow.value = e
              queryExportModelList()
              identifyBatchModalVisible.value = true
            }
          },
          { default: () => '登记' }
        )
      ]
    }
  ].filter((e) => (isTF.value ? e.key !== 'identifyValue' : true))
})

const queryDetailTableData = async () => {
  try {
    detailTableLoading.value = true
    const [error, res] = await sendRequest<HttpResponsePagination<IdentifySubItemModel>>({
      module: 'batch',
      api: 'identifySubItems',
      override: {
        params: {
          identifyId: baseInfo.value.id,
          limit: 10000000,
          page: 1
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    detailTableData.value = res.data.list
  } catch (error) {
    console.log(error)
  } finally {
    detailTableLoading.value = false
  }
}

const attachmentsLoading = ref(false)
const attachments = ref({} as any)
const queryAttachments = async () => {
  try {
    attachmentsLoading.value = true
    const [error, res] = await sendRequest<HttpResponse>({
      module: 'batch',
      api: 'identifyRegisterDetail',
      override: {
        params: {
          identifyId: baseInfo.value.id
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    attachments.value = res.data
    formData.value.totalOpinion = res.data.totalOpinion
    formData.value.remark = res.data.remark
    filesFormData.forEach((e) => {
      const files = res.data[e.key.replace('Ids', 's')]
      if (!files) return
      e.defaultValue = files.map((e: any) => ({
        id: e.id,
        status: 'finished',
        name: e.name,
        url: e.path,
        remoteId: e.id
      }))
    })
  } catch (error) {
    console.error(error)
  } finally {
    attachmentsLoading.value = false
  }
}

const filesFormInst = shallowRef<FormInst | null>(null)
const filesFormData = reactive<
  {
    label: string
    key: string
    required?: boolean
    value: UploadFileInfo[]
    defaultValue?: UploadFileInfo[]
  }[]
>([
  {
    label: '鉴定方案',
    key: 'planFileIds',
    value: [],
    required: true
  },
  {
    label: '专家鉴定意见',
    key: 'expertFileIds',
    value: [],
    required: true
  },
  {
    label: '汇总鉴定意见',
    key: 'summaryResultFileIds',
    value: [],
    required: true
  },
  {
    label: '会议汇报材料',
    key: 'meetingResultFileIds',
    value: [],
    required: true
  },
  {
    label: '会议纪要材料',
    key: 'meetingMinutesFileIds',
    value: [],
    required: true
  },
  {
    label: '合同和发票材料',
    key: 'contractFileIds',
    value: []
  },
  {
    label: '视频材料',
    key: 'videoFileIds',
    value: []
  },
  {
    label: '音频材料',
    key: 'audioFileIds',
    value: []
  },
  {
    label: '其他材料',
    key: 'otherFileIds',
    value: []
  },
  {
    label: '价格结果材料',
    key: 'priceFileIds',
    value: [],
    required: true
  },
  {
    label: '谈判会材料',
    key: 'talkFileIds',
    value: [],
    required: true
  }
])
const handleUploadFinish = (key: string, e: UploadFileInfo[]) => {
  const target = filesFormData.find((e) => e.key === key)
  if (!target) return
  target.value = e
  // filesFormInst.value?.validate(
  //   () => {},
  //   (rule) => {
  //     return rule?.key === key
  //   }
  // )
}

// const validatorFile = (_: string, value: CustomFile[]) => {
//   if (!value.length) {
//     return new Error('请上传该附件')
//   }
//   return true
// }

const createLimitRule = (len: number): FormItemRule => {
  return {
    trigger: ['blur', 'input'],
    message: `不能超过${len}字`,
    validator: (_, value) => {
      console.log(value)
      return value ? value.length <= len : true
    }
  }
}

const expertList = ref<any[]>([])
const expertLoading = ref(false)
const queryExpertLIst = async () => {
  try {
    expertLoading.value = true
    const [error, res] = await sendRequest<HttpResponse<any[]>>({
      module: 'batch',
      api: 'expertList',
      override: {
        params: {
          identifyId: baseInfo.value.id
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    expertList.value = res.data
  } catch (error) {
    console.error(error)
  } finally {
    expertLoading.value = false
  }
}

const exportModelList = ref<any[]>([])
const exportModelLoading = ref(false)
const queryExportModelList = async () => {
  try {
    exportModelLoading.value = true
    const [error, res] = await sendRequest<HttpResponse<any[]>>({
      module: 'batch',
      api: 'expertList',
      override: {
        params: {
          identifyId: baseInfo.value.id,
          subItemId: activeTableRow.value?.id
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    exportModelList.value = res.data
    setIdentifyBatchFormData()
  } catch (error) {
    console.error(error)
  } finally {
    exportModelLoading.value = false
  }
}

const valueRule: FormItemRule = {
  required: true,
  trigger: ['blur', 'input'],
  validator: (_, value) => {
    if (!isDefine) return new Error('评估价格必填，请输入')
    if (!isDefine(value.minIdentifyValue)) return new Error('最低价格必填，请输入')
    if (!isDefine(value.maxIdentifyValue)) return new Error('最高价格必填，请输入')
    if (value.minIdentifyValue > value.maxIdentifyValue)
      return new Error('最低价格不能大于最高价格')
    if (value.minIdentifyValue < 0) return new Error('价格不能小于0')
    return true
  }
}

onMounted(() => {
  queryClueMethodOptions()
  queryClueSelectOptions()
  queryBatchInfo()
  queryBaseInfo()
  queryExpertLIst()
})
</script>

<template>
  <div class="register-tf">
    <template v-if="!isFromRecord">
      <div class="itf-card identity-flow">
        <div class="step finished">提交鉴定</div>
        <NIcon
          color="#6CB187"
          size="32"
        >
          <ArrowRightAltFilled />
        </NIcon>
        <div class="step finished">鉴定登记</div>
        <NIcon
          color="#6CB187"
          size="32"
        >
          <ArrowRightAltFilled />
        </NIcon>
        <div class="step">鉴定结束</div>
      </div>

      <div class="br"></div>
    </template>

    <div class="rtf-title">鉴定信息</div>
    <DetailFormProvider>
      <NForm
        disabled
        label-placement="left"
        label-width="100rem"
        :show-feedback="false"
        :show-require-mark="false"
        class="rtf-card grid"
      >
        <NFormItem label="鉴定编号：">
          <NInput
            placeholder="/"
            :value="baseInfo.identifyCode"
          />
        </NFormItem>
        <NFormItem label="鉴定名称：">
          <NInput
            placeholder="/"
            :value="baseInfo.identifyName"
          />
        </NFormItem>
        <NFormItem label="鉴定日期：">
          <NInput
            placeholder="/"
            :value="baseInfo.identifyTime"
          />
        </NFormItem>
        <NFormItem label="鉴定地点：">
          <NInput
            placeholder="/"
            :value="baseInfo.identifyAddress"
          />
        </NFormItem>
        <NFormItem label="鉴定类型：">
          <NInput
            placeholder="/"
            :value="baseInfo.identifyType"
          />
        </NFormItem>
        <NFormItem label="鉴定专家：">
          <NSelect
            :options="expertList"
            :loading="expertLoading"
            :value="baseInfo.identifyExpertIds?.split(',')"
            multiple
            label-field="userName"
            value-field="id"
            placeholder="/"
          />
        </NFormItem>
        <NFormItem label="描述：">
          <NInput
            placeholder="/"
            type="textarea"
            rows="1"
            :value="baseInfo.identifyDescription"
          />
        </NFormItem>
        <NFormItem label="附件：">
          <FileList :fileList="fileList" />
        </NFormItem>
      </NForm>
    </DetailFormProvider>

    <div class="br"></div>

    <div class="rtf-title">批次信息</div>
    <DetailFormProvider>
      <NForm
        disabled
        label-placement="left"
        label-width="100rem"
        :show-feedback="false"
        :show-require-mark="false"
        class="rtf-card form"
      >
        <NFormItem label="关联线索：">
          <NSelect
            :value="batchInfo.clueId"
            :options="clueSelectOptions"
            :loading="clueSelectLoading"
            placeholder="/"
          />
        </NFormItem>
        <NFormItem label="批次名称：">
          <NTooltip :max-width="350">
            <template #trigger>
              <NInput
                :value="batchInfo.name"
                placeholder="/"
              />
            </template>
            {{ batchInfo.name }}
          </NTooltip>
        </NFormItem>
        <NFormItem label="征集方式：">
          <NTreeSelect
            :value="batchInfo.solicitMethodCode"
            :options="clueMethodOptions"
            :loading="clueMethodLoading"
            placeholder="/"
            key-field="code"
            label-field="name"
          />
        </NFormItem>
        <NFormItem label="接收时间：">
          <NDatePicker
            :formatted-value="batchInfo.receiveTime"
            type="datetime"
            placeholder="/"
          />
        </NFormItem>
        <NFormItem label="接收人：">
          <NInput
            :value="batchInfo.receiver"
            placeholder="/"
          />
        </NFormItem>
        <NFormItem label="征集数量：">
          <NInputNumber
            :value="batchInfo.solicitNum"
            placeholder="/"
            :show-button="false"
            :min="0"
            :max="Number.MAX_SAFE_INTEGER"
          />
        </NFormItem>
        <NFormItem label="证书发放：">
          <BatchCres :batch-id="batchInfo.id" />
        </NFormItem>
        <template v-if="batchInfo.solicitMethodCode == 'A3007'">
          <NFormItem label="开始时间：">
            <NDatePicker
              :formatted-value="batchInfo.startTime"
              type="date"
              placeholder="/"
            />
          </NFormItem>
          <NFormItem label="结束时间：">
            <NDatePicker
              :formatted-value="batchInfo.endTime"
              type="date"
              placeholder="/"
            />
          </NFormItem>
          <NFormItem label="代存期限：">
            <NInput
              :value="batchInfo.depositPeriod"
              placeholder="/"
            />
          </NFormItem>
        </template>

        <NFormItem label="藏家：">
          <NInput
            v-model:value="collectorName"
            placeholder="/"
            disabled
          />
        </NFormItem>
        <NFormItem label="移交人：">
          <NInput
            v-model:value="batchInfo.transferor"
            placeholder="/"
            disabled
            style="flex-shrink: 2"
          />
          <NInput
            v-model:value="batchInfo.transferorPhone"
            placeholder="/"
            disabled
          />
        </NFormItem>

        <NFormItem label="创建时间：">
          <NDatePicker
            :formatted-value="batchInfo.createTime"
            type="datetime"
            placeholder="/"
          />
        </NFormItem>
        <NFormItem label="修改时间：">
          <NDatePicker
            :formatted-value="batchInfo.modifyTime"
            type="datetime"
            placeholder="/"
          />
        </NFormItem>
        <NFormItem label="鉴定状态：">
          <NInput
            :value="batchInfo.identifyStatus"
            placeholder="/"
          />
        </NFormItem>

        <NFormItem
          label="备注："
          class="n-form-item--textarea"
        >
          <NInput
            :value="batchInfo.remark"
            type="textarea"
            placeholder="/"
            rows="5"
          />
        </NFormItem>
        <NFormItem label="附件：">
          <VAttachments
            v-if="batchInfo.fileIds"
            :attach-list="batchFileList"
          />
        </NFormItem>
      </NForm>
    </DetailFormProvider>

    <template v-if="isTF">
      <div class="br"></div>

      <div class="rtf-title">
        <span>汇总结果</span>
        <NButton
          color="#5FB17F"
          ghost
          :disabled="editTableIds.length === 0"
          @click="summaryBatchModalVisible = true"
          style="margin-right: 20px"
        >
          批量登记
        </NButton>
      </div>

      <NDataTable
        :loading="tableLoading"
        :data="tableData"
        :columns="columns"
        :row-key="(row) => row.id"
        @update-checked-row-keys="($event) => (editTableIds = ($event as number[]))"
        max-height="200rem"
        class="rtf-card"
      />

      <NForm
        ref="hzFormInst"
        :model="formData"
        label-placement="left"
        label-width="130rem"
        require-mark-placement="left"
        inline
        class="rtf-card grid"
      >
        <NFormItem
          label="鉴定汇总意见："
          path="totalOpinion"
          :rule="{ required: true, message: '鉴定汇总意见必填，请输入', trigger: 'blur' }"
        >
          <NInput
            placeholder="请输入"
            v-model:value="formData.totalOpinion"
          />
        </NFormItem>
        <NFormItem label="备注：">
          <NInput
            placeholder="请输入"
            type="textarea"
            rows="1"
            v-model:value="formData.remark"
          />
        </NFormItem>
        <!-- <NFormItem style="justify-self: end">
          <NButton
            color="#5FB17F"
            ghost
            :disabled="editTableIds.length === 0"
            @click="summaryBatchModalVisible = true"
          >
            批量登记
          </NButton>
        </NFormItem> -->
      </NForm>

      <NModal
        :auto-focus="false"
        v-model:show="summaryBatchModalVisible"
      >
        <ModalCard
          @submit="handleSummaryBatchModalSubmit"
          @close="handleSummaryBatchModalClose"
          :loading="summaryBatchModalLoading"
          action
          title="登记"
        >
          <div class="sbmc-wrapper">
            <NForm
              ref="summaryBatchModalFormInst"
              class="sbmc"
              label-placement="left"
              require-mark-placement="left"
              label-width="100rem"
              :model="summaryBatchModalFormData"
            >
              <NFormItem
                label="征集品真伪"
                path="authenticity"
                :rule="{ required: true, message: '征集品真伪必填，请选择' }"
              >
                <NSelect
                  v-model:value="summaryBatchModalFormData.authenticity"
                  placeholder="请选择"
                  :options="[
                    { label: '真', value: '0' },
                    { label: '伪', value: '1' },
                    { label: '无法确定', value: '2' }
                  ]"
                />
              </NFormItem>
              <NFormItem
                label="意见"
                path="opinion"
                :rule="createLimitRule(20)"
              >
                <NInput
                  v-model:value="summaryBatchModalFormData.opinion"
                  placeholder="请输入"
                  type="textarea"
                  rows="5"
                />
              </NFormItem>
            </NForm>
          </div>
        </ModalCard>
      </NModal>
    </template>

    <div class="br"></div>

    <div class="rtf-title">
      <span>鉴定清单</span>
      <NButton
        color="#5FB17F"
        ghost
        style="display: flex; margin-right: 20px"
        :disabled="!checkIds.length"
        @click="handleIdentifyBatchModalOpen"
      >
        批量登记
      </NButton>
    </div>

    <NDataTable
      :loading="detailTableLoading"
      :data="detailTableData"
      :columns="detailColumns"
      :row-key="(row) => row.id"
      @update-checked-row-keys="($event) => (checkIds = ($event as number[]))"
      max-height="200rem"
      class="rtf-card"
    />
    <NModal
      v-model:show="identifyBatchModalVisible"
      :auto-focus="false"
    >
      <ModalCard
        @submit="handleIdentifyBatchModalSubmit"
        @close="handleIdentifyBatchModalClose"
        :loading="identifyBatchModalLoading"
        action
        title="登记"
        title-style="padding-bottom: 10rem"
      >
        <NScrollbar style="max-height: 80vh">
          <div class="sbmc-wrapper">
            <span class="rtf-title-global">物品信息</span>
            <NForm
              class="sbmc grid"
              label-placement="left"
              :show-feedback="false"
            >
              <template
                v-for="(item, i) in identifyBatchInfos"
                :key="i"
              >
                <NFormItem label="征集品编码：">
                  <NInput
                    disabled
                    placeholder="/"
                    :value="item.subItemCode"
                    style="min-width: 200rem"
                  />
                </NFormItem>
                <NFormItem label="征集品名称：">
                  <NInput
                    disabled
                    placeholder="/"
                    :value="item.itemName"
                  />
                </NFormItem>
                <NFormItem label="类型：">
                  <NInput
                    disabled
                    placeholder="/"
                    :value="item.itemType"
                  />
                </NFormItem>
              </template>
            </NForm>

            <div class="br-global"></div>

            <span class="rtf-title-global">鉴定结果</span>

            <NForm
              ref="identifyBatchFormInst"
              class="sbmc grid"
              label-placement="left"
              require-mark-placement="left"
              label-width="100rem"
              :model="identifyBatchFormData"
            >
              <template
                v-for="(item, i) in identifyBatchFormData"
                :key="item.expertId"
              >
                <NFormItem label="鉴定专家：">
                  <NSelect
                    :options="exportModelList"
                    :loading="exportModelLoading"
                    disabled
                    placeholder="/"
                    label-field="userName"
                    value-field="id"
                    :value="item.expertId"
                  />
                </NFormItem>
                <NFormItem
                  v-if="isTF"
                  label="物品真伪："
                  :path="`${i}[status]`"
                  :rule="{
                    required: true,
                    message: '物品真伪必填，请选择',
                    type: 'number',
                    trigger: ['change', 'blur']
                  }"
                >
                  <NRadioGroup v-model:value="item.status">
                    <NRadioButton :value="0">真</NRadioButton>
                    <NRadioButton :value="1">伪</NRadioButton>
                    <NRadioButton :value="2">无法确定</NRadioButton>
                  </NRadioGroup>
                </NFormItem>
                <NFormItem
                  v-else
                  label="评估价格："
                  :path="`${i}`"
                  :rule="valueRule"
                  style="max-width: 400px"
                >
                  <NInputNumber
                    v-model:value="item.minIdentifyValue"
                    :min="0"
                    :max="999999999"
                    :precision="2"
                    :show-button="false"
                    placeholder="最低价格"
                  />
                  <span>-</span>
                  <NInputNumber
                    v-model:value="item.maxIdentifyValue"
                    :min="item.minIdentifyValue || 0"
                    :max="999999999"
                    :precision="2"
                    :show-button="false"
                    placeholder="最高价格"
                  />
                  <span>&nbsp;元</span>
                </NFormItem>
                <NFormItem
                  label="意见："
                  :path="`${i}[opinion]`"
                  :rule="createLimitRule(20)"
                >
                  <NInput
                    type="textarea"
                    rows="1"
                    placeholder="请输入"
                    v-model:value="item.opinion"
                  />
                </NFormItem>
              </template>
            </NForm>
          </div>
        </NScrollbar>
      </ModalCard>
    </NModal>

    <div class="br"></div>

    <div class="rtf-title">附件</div>
    <NForm
      ref="filesFormInst"
      :model="filesFormData"
      class="rtf-card attachment-grid"
      require-mark-placement="left"
      label-placement="left"
    >
      <div
        v-for="(item, i) in filesFormData"
        :key="i"
        class="attachment"
      >
        <div class="attachment-title">{{ item.label }}</div>
        <!--    :path="`${i}[value]`"
          :rule="
            item.required
              ? {
                  required: true,
                  key: item.key,
                  validator: () => validatorFile(item.key, item.value)
                }
              : undefined
          " -->
        <NFormItem label="附件：">
          <FUploader
            v-if="!isFromRecord || (isFromRecord && !attachmentsLoading)"
            :max="10"
            :file-list="item.value"
            @update:file-list="(e) => handleUploadFinish(item.key, e)"
          />
        </NFormItem>
      </div>
    </NForm>
  </div>

  <FixedAction>
    <div class="register-tf-buttons">
      <NButton
        color="#999999"
        ghost
        :disabled="submitLoading"
        @click="routeReplace"
        style="width: 78px; height: 34px"
      >
        取消
      </NButton>

      <NButton
        color="#5FB17F"
        :disabled="submitLoading"
        :loading="submitLoading"
        @click="handleSubmit"
        style="width: 78px; height: 34px"
      >
        确定
      </NButton>
    </div>
  </FixedAction>
</template>

<style lang="scss">
.identity-flow {
  display: flex;
  align-items: center;
  gap: 0 1.5em;

  .step {
    padding: 10rem 15rem;
    background-color: #e1e1e1;

    &.finished {
      color: #fff;
      background-color: #6cb187;
    }
  }
}

.br-global {
  position: relative;
  width: 100%;
  padding: 30rem 0;

  &::after {
    content: '';
    position: absolute;
    width: 100%;
    top: 50%;
    left: 0;
    border-top: 1px dotted #bc9e70;
    transform: translateY(-50%);
  }
}
</style>
<style scoped lang="scss">
.register-tf {
  min-height: 100%;
  padding: 15rem 0 110rem;
  background-color: #f0efee;

  :deep(.n-data-table__pagination) {
    justify-content: flex-start;
  }

  .br {
    position: relative;
    width: 100%;
    padding: 30rem 0;

    &::after {
      content: '';
      position: absolute;
      width: 100%;
      top: 50%;
      left: 0;
      border-top: 1px dotted #bc9e70;
      transform: translateY(-50%);
    }
  }

  .rtf-card {
    padding: 20rem;
    background-color: #e1e1e1;

    &.form {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: 16rem 32rem;

      .n-form-item--textarea {
        grid-column: 1 / -1;
      }

      .n-date-picker,
      .n-input-number {
        flex: 1;
      }
    }
  }

  .n-form.grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16rem 32rem;
  }

  .n-form.attachment-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 10rem 15rem;
    padding: 20rem 30rem;

    .attachment {
      &-title {
        margin-bottom: 0.5em;
        font-weight: 600;
        font-size: 16rem;
      }

      .n-form-item {
        margin-left: 2em;
      }
    }
  }

  .rtf-title,
  :global(.rtf-title-global) {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    font-size: 26rem;
    margin-bottom: 30rem;
    color: #048c5e;
    line-height: 1;
  }

  :global(.rtf-title-global) {
    font-size: 16rem;
    margin-bottom: 12rem;
  }

  .rtf-steps {
    padding: 20rem 50% 20rem 20rem;
    margin-top: 15rem;
  }
}

.register-tf-buttons {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0 16rem;

  .n-button {
    width: 100rem;
    height: 50rem;
  }
}

.sbmc-wrapper {
  min-width: 600rem;
  padding: 30rem 44rem 0;
}
.sbmc {
  padding: 30rem 35rem 30rem;
  background-color: #ebeceb;

  &.grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 0 30rem;
  }
}
</style>
